package com.shangyueshang.security;

import com.shangyueshang.utils.PasswordEncoder;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2022/1/6 18:48
 * @version: v1.0.0
 * <p>
 * 身份验证提供者
 */
public class JwtAuthenticationProvider extends DaoAuthenticationProvider {

    public JwtAuthenticationProvider(UserDetailsService userDetailsService) {
        setUserDetailsService(userDetailsService);
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            super.logger.debug("Failed to authenticate since no credentials provided");
            throw new BadCredentialsException(
                    super.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")
            );
        }
        String presentedPassword = authentication.getCredentials().toString();
        String salt = ((JwtUserDetails) userDetails).getSalt();
        //重写密码验证逻辑
        if (!new PasswordEncoder(salt).matches(userDetails.getPassword(), presentedPassword)) {
            super.logger.debug("Failed to authenticate since password does not match stored value");
            throw new BadCredentialsException(
                    super.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")
            );
        }
    }
}
